<template>
	<div class="html-parser">
		<rich-text selectable preview image-menu-prevent :nodes='nodes' />
	</div>
</template>

<script setup>
	import URL from 'url';
	import { ref, watch } from 'vue';
	import file from '@/utils/file/index.js'
	import htmlParser from './html-parser.js';
	import tools from '@/utils/tools/index.js'

	const test = uni.$uv.test;
	const props = defineProps({
		html: {
			type: String,
			default: ''
		}
	})

	const nodes = ref([]);

	function richHandle(nodes) {
		return nodes.map(item => {
			if (test.array(item.children)) {
				item.children = richHandle(item.children);
			}

			if (item['name']) {
				!item['attrs'] && (item['attrs'] = {});
				item['attrs']['class'] = item['name'];
			}

			try {
				// 修改图片请求域名
				const src = test.object(item['attrs']) && item['attrs']['src'];
				if (item['name'] === 'img' && src) {
					const { path } = URL.parse(src);
					console.log(path);
					item['attrs']['src'] = file.getFileUrl(path)
				}
			} catch {}

			return item;
		})
	}

	watch(() => props.html, (val) => {
		val && (nodes.value = richHandle(htmlParser(val)));
	}, { immediate: true })
</script>

<style lang="scss">
	.html-parser {
		word-wrap: break-word;
		font-size: 28rpx;
		line-height: 1.6;
		text-align: justify;
		word-break: break-all;

		.img {
			border-radius: 4px;
			max-width: 100%;
			height: auto;
		}

		.div,
		.p {
			word-wrap: break-word;
			line-height: 1.6;
			padding-bottom: 30rpx;
			word-break: break-all;

			&:last-child {
				padding-bottom: 0;
			}
		}

		.a {
			text-decoration: none;
		}

		.ul,
		.ol {
			margin: 0;
			padding: 0;
			padding-left: 40rpx;
			padding-bottom: 30rpx;
		}

		.h1 {
			font-size: 64rpx;
			padding-bottom: 30rpx;
		}

		.h2 {
			font-size: 48rpx;
			padding-bottom: 30rpx;
		}

		.h3 {
			font-size: 36rpx;
			padding-bottom: 30rpx;
		}

		.h4 {
			font-size: 32rpx;
			padding-bottom: 30rpx;
		}

		.h5 {
			font-size: 26rpx;
			padding-bottom: 30rpx;
		}

		.h6 {
			font-size: 24rpx;
			padding-bottom: 30rpx;
		}
	}
</style>